<template>
    <div class="loginbody">
        <el-tooltip content="背景切换" placement="top-start">
            <div class="changeBg" @click="changeBg">
                <i class="el-icon-setting"></i>
            </div>
        </el-tooltip>

        <div class="bg" v-if="type == 1">
            <video-box :videoUrl.sync="login1" ref="videoBox" />
        </div>
        <div class="bg" v-if="type == 2">
            <video-box :videoUrl.sync="login2" ref="videoBox1" />
        </div>
        <div class="bg" v-if="type == 3">
            <video-box :videoUrl.sync="login3" ref="videoBox2" />
        </div>
        <div class="mask"></div>
        <img src="@/assets/images/login/top.png" class="imgTop" />
        <div class="imgBottom">Copyright©2020-2025&nbsp;湖南卓强物联科技有限公司版权所有&nbsp;&nbsp; 服务热线：400-932-9896</div>
        <div class="rightLogin">
            <div class="loginText">登录</div>
            <div class="subText">欢迎登录AIoT³超融合中枢平台</div>
            <div class="btns">
                <div :class="showUser ? 'selectBtn' : ''" @click="showUser = true">用户名</div>
                <div :class="!showUser ? 'selectBtn' : ''" @click="showUser = false">手机号</div>
            </div>
            <div class="user username" v-if="showUser">
                <el-input
                    @keyup.enter.native="userLogin"
                    placeholder="请输入帐号"
                    maxlength="20"
                    minlength="4"
                    v-model="username"
                    clearable
                >
                </el-input>
            </div>
            <div class="user username" v-if="!showUser">
                <el-input type="tel" placeholder="请输入手机号" maxlength="11" v-model="tel" clearable> </el-input>
            </div>
            <div class="user password" v-if="showUser">
                <el-input
                    @keyup.enter.native="userLogin"
                    placeholder="请输入密码"
                    maxlength="16"
                    minlength="5"
                    v-model="password"
                    show-password
                    clearable
                ></el-input>
            </div>
            <div v-if="showUser" style="height: 40px">
                <div class="user" style="width: 70%; float: left">
                    <el-input @keyup.enter.native="userLogin" placeholder="请输入验证码" maxlength="4" v-model="code" clearable></el-input>
                </div>
                <div class="user" style="width: 25%; float: right; cursor: pointer">
                    <img :src="base64Img" style="height: 100%; width: 100%; cursor: pointer" @click="getCode" />
                </div>
            </div>
            <div v-if="!showUser" style="height: 40px">
                <div class="user" style="width: 50%; float: left">
                    <el-input placeholder="请输入验证码" maxlength="6" v-model="dxYzm" clearable></el-input>
                </div>
                <div class="user" style="width: 45%; float: right">
                    <el-button type="default" class="btnGetYzm">获取验证码</el-button>
                </div>
            </div>
            <div class="ver">UKEY验证</div>
            <div class="agree">
                <el-checkbox v-model="checked" size="medium"></el-checkbox>
                登录即代表阅读并同意 <a>用户协议</a>
            </div>
            <div class="loginBtn" @click="userLogin">登录</div>
            <div class="other">
                <div class="line"></div>
                <div class="otherName">其他方式</div>
                <div class="line"></div>
            </div>
            <div class="wx" @click="handleOpenWxLogin">
                <img src="@/assets/images/login/wxLogo.png" />
            </div>
        </div>
        <el-dialog title="" :visible.sync="dialogVisible" width="400px" :before-close="handleClose">
            <div class="qrcode-container">
                <img src="@/assets/images/login/wx.png" alt="" />
                <!-- <canvas ref="qrcodeCanvas"></canvas> -->
            </div>
            <!-- <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="handOpenWxLogin()">确 定</el-button>
            </span> -->
        </el-dialog>

        <el-dialog title="请选择组织机构" :visible.sync="orgDialogVisible" width="400px" :before-close="orgHandleClose">
            <el-input
                placeholder="请输入机构"
                v-model="orgName"
                class="input-with-select"
                @change="orgInput"
                @keyup="orgInput"
                style="width: 90%; height: 32px; padding: 0; margin: 10px 5%"
            >
                <el-button slot="append" icon="el-icon-search" @click="orgInput"></el-button>
            </el-input>
            <div
                style="
                    max-height: 400px;
                    overflow-y: auto;
                    overflow-x: hidden;
                    display: flex;
                    flex-direction: column;
                    gap: 10px;
                    justify-content: center;
                    align-items: center;
                "
            >
                <el-button
                    style="width: 90%; height: 32px; padding: 0; margin: 0"
                    v-for="item in orgList"
                    v-bind:key="item.OrgId"
                    @click="selectOrg(item, loginInfo)"
                    >{{ item.OrgName }}
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import loginOneMp4 from '@/assets/images/login/login1.mp4'
import loginTwoMp4 from '@/assets/images/login/login2.mp4'
import loginThreeMp4 from '@/assets/images/login/login3.mp4'
import videoBox from '@/components/videoBox'
import {AjaxCommon} from '@/libs/apiCommon'
import {PopupCommon} from '@/libs/popupCommon'
import {Utility} from '@/libs/utility'
import axios from 'axios'
import QRCode from 'qrcode'
import {setToken} from '@/libs/util'
import {mapActions} from 'vuex'
export default {
    name: 'userLogin',
    components: {
        videoBox
    },
    data() {
        return {
            orgName: '',
            guid: '',
            type: 1,
            login1: loginOneMp4,
            login2: loginTwoMp4,
            login3: loginThreeMp4,
            checked: true,
            tel: '',
            // username: 'supper_admin',
            // password: 'ZQZN@2025',
            username: '',
            password: '',
            dxYzm: '',
            code: '',
            base64Img: '',
            showUser: true,
            dialogVisible: false,
            orgDialogVisible: false,
            orgList: [],
            orgAllList: [],
            loginInfo: {}
        }
    },
    mounted() {
        this.$nextTick(() => {
            this.getCode()
        })
    },
    created() {},
    methods: {
        orgInput(e) {
            const data = this.orgAllList.filter((t) => t.OrgName.indexOf(e) != -1)
            this.orgList = data
        },
        changeBg() {
            if (this.type == 1) {
                this.type = 2
            } else if (this.type == 2) {
                this.type = 3
            } else {
                this.type = 1
            }
        },
        // web微信登录
        handOpenWxLogin() {
            this.dialogVisible = false
            const url =
                'https://open.weixin.qq.com/connect/qrconnect?appid=你的APPID&redirect_uri=你的回调地址&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect'
            QRCode.toCanvas(this.$refs.qrcodeCanvas, url, (error) => {
                if (error) console.error(error)
                console.log('二维码已生成')
            })
        },
        handleClose() {
            this.dialogVisible = false
        },
        orgHandleClose() {
            this.orgDialogVisible = false
        },
        // 打开微信登录
        handleOpenWxLogin() {
            this.dialogVisible = true
        },
        userLogin() {
            if (!this.checked) {
                PopupCommon.notify('info', '请勾选用户协议')
                return
            }
            if (this.showUser) {
                if (this.username.trim() == '') {
                    PopupCommon.notify('info', '请输入帐号')
                    return
                }
                if (this.username.trim().length < 4) {
                    PopupCommon.notify('info', '用户名需4-20位')
                    return
                }
                if (this.password.trim() == '') {
                    PopupCommon.notify('info', '请输入密码')
                    return
                }
                if (this.password.trim().length < 5) {
                    PopupCommon.notify('info', '密码需5-16位')
                    return
                }
                if (this.code.trim() == '') {
                    PopupCommon.notify('info', '请输入验证码')
                    return
                }
                if (this.code.trim().length != 4) {
                    PopupCommon.notify('info', '请输入4位数字的验证码')
                    return
                }
                let that = this
                // 判断验证码是否正确
                axios
                    .post(`/api/auth/VerifyCode/${this.guid}/${this.code.trim()}`, {}, {})
                    .then(() => {
                        this.toPwdLogin()
                    })
                    .catch((error) => {
                        that.code = ''
                        that.getCode()
                        PopupCommon.notify('info', error.response.data.Message)
                    })
            } else {
                if (this.tel.trim() == '') {
                    PopupCommon.notify('info', '请输入手机号')
                    return
                }
                if (this.dxYzm.trim() == '') {
                    PopupCommon.notify('info', '请输入验证码')
                    return
                }
            }
        },
        getCode() {
            const guid = Utility.getGUID()
            this.guid = guid
            let that = this
            AjaxCommon('/api/auth/GenerateCode/' + guid, 'get', null).then((res) => {
                const str = res.data.ImageData
                const type = res.data.MimeType
                const baseImg = `data:${type};base64,${str}`
                that.base64Img = baseImg
            })
        },
        ...mapActions(['getUserInfo']),
        // 用户名密码登录的方式
        /**
         * supper_admin  ZQZN@2025
         * yykjzy_admin  yykjzy1@admin
         * zq13307318488 Zq@13307318488
         */
        toPwdLogin() {
            axios
                .post(
                    `/api/Auth/Login`,
                    {
                        USER_NAME: this.username,
                        USER_PASSWORD: this.password,
                        ValidateCode: this.code
                    },
                    {}
                )
                .then((res) => {
                    if (res.data?.Head?.ItemCount == 0) {
                        PopupCommon.notify('info', res.data.Head.ErrMsg)
                        return
                    }
                    if (res.data?.UName) {
                        this.loginInfo = res.data
                        // const orgList = res.data?.Organization[0]
                        // // OrgId OrgName
                        // for (let index = 0; index < 6; index++) {
                        //     const newOrg = {...orgList, OrgId: orgList.OrgId + index, OrgName: orgList.OrgName + index}
                        //     res.data.Organization.push(newOrg)
                        // }
                        // 登录成功了,如果有两个及其以上的组织，弹出组织列表供选择
                        if (res.data?.Organization?.length >= 2) {
                            //
                            this.orgList = res.data?.Organization
                            this.orgAllList = res.data?.Organization
                            this.orgDialogVisible = true
                        } else {
                            this.selectOrg(res.data?.Organization[0], res.data)
                        }
                    }
                })
                .catch((error) => {
                    PopupCommon.notify('info', error.response.data.Message)
                })
        },
        selectOrg(item, othderData) {
            this.loginInfo.orgItem = item
            var userInfo = {
                userId: item.UserId,
                // 个人中心需要
                // userGuid:item.UserGuid,
                orgId: item.OrgId,
                orgName: item.OrgName,
                username: this.loginInfo.UName,
                realname: this.loginInfo.URealName,
                phonenumber: othderData.UTel,
                email: othderData.UEmail,
                sex: othderData.USER_SEX,
                address: othderData.UAddress,
                role: item.UserRoles.join(','),
                avatar: 'https://static.jeecg.com/temp/国炬软件logo_1606575029126.png',
                token: this.loginInfo.Token,
                roleList: othderData.orgItem.UserRoles
            }
            localStorage.setItem('userInfo', JSON.stringify(userInfo))
            setToken(userInfo.token)
            sessionStorage.setItem('ALLMENULIST', '')
            sessionStorage.setItem('menuInfo', '')

            // this.getUserInfo().then((res) => {
            this.$router.push({
                name: 'indexMain'
            })
            // })
        }
    }
}
</script>

<style lang="scss">
.loginbody {
    position: relative;
    height: 100vh;
    width: 100vw;

    .changeBg {
        position: absolute;
        z-index: 3;
        top: 20px;
        right: 20px;
        cursor: pointer;
        background-color: #4b63f5;
        color: #fff;
        padding: 5px 10px;
        text-align: center;
        border-radius: 4px;
    }

    .bg {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: 1;
    }

    .mask {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: 2;
        background-color: transparent;
    }

    .imgTop {
        position: absolute;
        top: 10px;
        left: 10px;
        z-index: 3;
    }

    .imgBottom {
        position: absolute;
        bottom: 40px;
        left: 0;
        width: 100%;
        text-align: center;
        z-index: 3;
        color: #fff;
        font-size: 18px;
    }

    .rightLogin {
        position: absolute;
        top: 50%;
        right: 0px;
        transform: translate(-35%, -50%);
        width: 200px;
        background-color: rgba(234, 240, 249, 0.85);
        border-radius: 20px;
        z-index: 3;
        padding: 50px 25px 5px 25px;
        text-align: left;
        width: 350px;

        .loginText {
            font-size: 30px;
            color: #000;
            margin-bottom: 10px;
        }

        .subText {
            font-size: 20px;
            color: #666;
            margin-bottom: 20px;
        }

        .btns {
            display: flex;
            gap: 2px;
            margin-bottom: 20px;

            div {
                flex: 1;
                height: 40px;
                line-height: 40px;
                text-align: center;
                font-size: 16px;
                color: #000;
                background-color: #fff;
                border-radius: 4px;
                cursor: pointer;
            }

            .selectBtn,
            div:hover {
                background-color: #4b63f5 !important;
                color: #fff !important;
            }
        }

        .user {
            height: 40px;
            line-height: 40px;
            border-radius: 4px;
            border: 1px solid rgba(153, 153, 153, 0.5);
            margin-bottom: 10px;

            &:hover,
            &:focus,
            &:active {
                border-color: #4b63f5 !important;
            }

            i {
                color: #666;
            }

            .el-input__inner {
                border: none;
                outline: none;
                background: transparent;
            }

            input::placeholder {
                color: #666;
            }
        }

        .password {
            position: relative;
        }

        .error {
            color: red;
            font-size: 14px;
            margin: 5px 0;
        }

        .ver {
            color: #4b63f5;
            cursor: pointer;
            text-align: right;
        }

        .loginBtn,
        .agree {
            clear: both;
            margin-top: -21px;

            .el-checkbox__inner {
                width: 18px;
                height: 18px;

                &::after {
                    height: 9px;
                    left: 5px;
                    width: 5px;
                }
            }
        }

        .agree a {
            color: #4b63f5;
            cursor: pointer;
        }

        .loginBtn {
            background-color: #4b63f5;
            color: #fff;
            cursor: pointer;
            height: 50px;
            text-align: center;
            line-height: 50px;
            width: 100%;
            font-size: 16px;
            letter-spacing: 2px;
            margin-top: 20px;
            border-radius: 4px;
        }

        .wx {
            background: #fff;
            width: 48px;
            height: 48px;
            border-radius: 48px;
            overflow: hidden;
            margin: 20px auto;
            cursor: pointer;
        }

        .other {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-top: 20px;

            .line {
                background-color: #a0a6b0;
                height: 1px;
                flex: 1;
            }

            .otherName {
                width: 100px;
                text-align: center;
                color: #888;
            }
        }
    }

    .qrcode-container {
        display: flex;
        justify-content: center;
        width: 100%;

        > img {
            width: 180px;
        }
    }

    .btnGetYzm {
        border: none;
        outline: none;
        width: 100%;
        height: 100%;
        background-color: transparent;
    }
}
</style>
